package com.tql.test_02;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test2 {
    public static void main(String[] args) {
        Tockit2 tockit2=new Tockit2();
        new Thread(()->{ for (int i = 0; i < 60; i++) tockit2.sale(); },"A").start();
        new Thread(()->{ for (int i = 0; i < 60; i++) tockit2.sale(); },"B").start();
        new Thread(()->{ for (int i = 0; i < 60; i++) tockit2.sale(); },"C").start();
    }
}
class Tockit2{
    int num=50;
    //可重入锁，默认是非公平锁
    Lock lock=new ReentrantLock();
    public synchronized void sale(){
        lock.lock();
        try {
            if(num>0){
                System.out.println(Thread.currentThread().getName()+"正在售卖第"+(num--)+"张票，剩余"+num);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}